package com.qianyitian.hope2.spider.lego;

import com.alibaba.fastjson.JSON;
import com.google.common.io.Files;
import com.qianyitian.hope2.spider.config.PropertyConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.text.MessageFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static java.text.MessageFormat.*;

@RestController
public class LegoController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource(name = "legoSpider")
    private LegoSpider legoSpider = null;

    @Autowired
    LegoStorageService storageService;

    @Autowired
    PropertyConfig config;

    @Scheduled(cron = "0 30 18 * * TUE,THU,SUN")
    //每周1-5 6:30:00 执行
    @Async
    @GetMapping("/lego/sets/refresh")
    public void retrieveStockDailyData() throws IOException {
        logger.info("scheduled to update lego stock status");
        legoSpider.updateStockStatus(getAll());
    }

    @GetMapping("/lego/sets/{country}")
    @CrossOrigin
    public List<LegoSet> getSetsByCountry(@PathVariable String country) throws IOException {
        List<LegoSet> all = getAll();

        if (country.equals("all")) {
            List<LegoSet> allList = new ArrayList<>();
            for (CountryEnum countryEnum : CountryEnum.values()) {
                allList.addAll(getSets(all, countryEnum.getAbbreviation()));
            }
            return allList;
        } else {
            return getSets(all, country);
        }
    }

    private List<LegoSet> getSets(List<LegoSet> all, String country) {
        List<LegoSet> list = all.parallelStream().map(one -> {
            String s = storageService.get(one.getCode(), country);
            LegoSet set = JSON.parseObject(s, LegoSet.class);
            return set;
        }).collect(Collectors.toList());
        return list;
    }


    public List<LegoSet> getAll() throws IOException {
        File file = new File(config.getDataPath(), "lego");
        List<String> list = Files.asCharSource(file, Charset.forName("UTF-8")).readLines();
        List<LegoSet> collect = list.stream().filter(item -> {
            return !StringUtils.isEmpty(item);
        }).map(item -> {
            String[] arrray = item.split(",");
            LegoSet set = new LegoSet(arrray[1], arrray[0]);
            return set;
        }).collect(Collectors.toList());
        return collect;
    }


    @GetMapping("/z/price/{amazonCode}")
    @CrossOrigin
    public String getZPrice(@PathVariable String amazonCode) throws IOException {
        String url = "https://www.amazon.cn/dp/{0}/";
        url = format(url, amazonCode);
        return legoSpider.getZPrice(url);
    }

//    @Scheduled(cron = "13 13 * * * *")
    @Async
    @GetMapping("/lego/amazon/notify")
    public void notifyAmazonPrice() throws IOException {
        legoSpider.notifyAmazonCheapPrice(getAllAmazonItem());
    }



    protected List<AmazonItem> getAllAmazonItem() throws IOException {
        File file = new File(config.getDataPath(), "amazon-lego");
        List<String> list = Files.asCharSource(file, Charset.forName("UTF-8")).readLines();
        List<AmazonItem> collect = list.stream().filter(item -> {
            return !StringUtils.isEmpty(item);
        }).map(item -> {
            String[] arrray = item.split(",");
            AmazonItem ai = new AmazonItem();
            ai.setBrief(arrray[0]);
            ai.setLegoCode(arrray[1]);
            ai.setProductCode(arrray[2]);
            ai.setOriginPrice(Double.valueOf(arrray[3]));
            ai.setNotifyPrice(Double.valueOf(arrray[4]));
            return ai;
        }).collect(Collectors.toList());


        return collect;
    }
}
